﻿using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using TConfig;

public class ExportSceneInfo {
	
	[MenuItem("Tools/Export Config/Current SceneObjs Info")]
	public static void ExportScene()
	{
		string path = Path.GetDirectoryName(Application.dataPath) + "/data/Configs";
		if(!Directory.Exists(path))
			Directory.CreateDirectory(path);
		
		GameObject[] sceneObjs = MonoBehaviour.FindObjectsOfType(typeof(GameObject)) as GameObject[];
		List<SceneObj> objList = new List<SceneObj>();
		string rootPath = "Assets/GameResources/Scene/";
		
		foreach(GameObject sceneObj in sceneObjs)
		{
			switch(PrefabUtility.GetPrefabType(sceneObj))
			{
			case PrefabType.DisconnectedModelPrefabInstance:
			case PrefabType.DisconnectedPrefabInstance:
			case PrefabType.MissingPrefabInstance:
				Debug.LogWarning("[Prefab lose] : " + sceneObj.name + " is losed it's prefab!", sceneObj);
				break;
			}
			
			GameObject prefab = PrefabUtility.GetPrefabParent(sceneObj) as GameObject;
			if(prefab != null)
			{
				if(prefab.transform.parent == null)
				{
					Transform trans = sceneObj.transform;
					SceneObj obj = new SceneObj();
					obj.name = sceneObj.name;
					string assetPath = AssetDatabase.GetAssetPath(prefab);
					string assetPathExtension = Path.GetExtension(assetPath);
					assetPath = assetPath.Substring(0, assetPath.Length - assetPathExtension.Length) + ".unity3d";
					if(assetPath.StartsWith(rootPath))
					{
						obj.prefabPath = assetPath.Substring(rootPath.Length);
						obj.parentName = (trans.parent != null) ? trans.parent.name : "";
						obj.positionX = trans.position.x;
						obj.positionY = trans.position.y;
						obj.positionZ = trans.position.z;
						obj.rotationX = trans.rotation.eulerAngles.x;
						obj.rotationY = trans.rotation.eulerAngles.y;
						obj.rotationZ = trans.rotation.eulerAngles.z;
						obj.scaleX = trans.lossyScale.x;
						obj.scaleY = trans.lossyScale.y;
						obj.scaleZ = trans.lossyScale.z;
						
						objList.Add(obj);
					}
				}
			}
		}
		
		string str = EditorApplication.currentScene;
		string sceneName = Path.GetFileNameWithoutExtension(str);
		string savePath = path + sceneName + "_SceneInfo.xml";
		XML<List<SceneObj>>.SaveAtPath(objList, savePath);
	}
}
